package com.veterinaria.dao;

import java.io.Reader;
import java.util.ArrayList;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.veterinaria.bean.ClienteBean;
import com.veterinaria.services.ClienteService;

public class ClienteDAO implements ClienteService{

	SqlSessionFactory sqlmapper= null;{
	   	 try {
		   	 Reader reader = Resources.getResourceAsReader("ConfiguracionIbatis.xml");
		   	 sqlmapper =new  SqlSessionFactoryBuilder().build(reader);
	   	 } catch (Exception e) {
			 e.printStackTrace();
  		 }
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public ArrayList<ClienteBean> listarClientes(ClienteBean cli) throws Exception {
		ArrayList<ClienteBean> lista = null;
		SqlSession session = sqlmapper.openSession();			
			try {
				lista= (ArrayList<ClienteBean>)session.selectList("clientexml.listarClientes",cli);
			} catch (Exception e) {
				e.printStackTrace();
			}finally{ session.close();}
		return lista;
	}

	@Override
	public ArrayList<ClienteBean> buscarClientes() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void grabarCliente(ClienteBean cli) throws Exception {
		 SqlSession session = sqlmapper.openSession();
			try {
				session.insert("clientexml.grabarCliente",cli);
				session.commit();
			} catch (Exception e) {
				e.printStackTrace();
				session.rollback();
			}finally{ session.close();}
	}
	
	@Override
	public void modificarCliente(ClienteBean cli) throws Exception {
		 SqlSession session = sqlmapper.openSession();
			try {
				session.update("clientexml.modificarCliente",cli);
				session.commit();
			} catch (Exception e) {
				e.printStackTrace();
				session.rollback();
			}finally{ session.close();}
	}

	@Override
	public void eliminarCliente(ClienteBean cli) throws Exception {
		 SqlSession session = sqlmapper.openSession();
			try {
				session.delete("clientexml.eliminarCliente",cli);
				session.commit();
			} catch (Exception e) {
				e.printStackTrace();
				session.rollback();
			}finally{ session.close();}
	}

	@Override
	public ClienteBean obtenerCliente(ClienteBean cli) throws Exception {
		ClienteBean cliente=null;
		SqlSession session = sqlmapper.openSession();			
		try {				
			cliente= (ClienteBean) session.selectOne("clientexml.obtenerCliente",cli);				
		} catch (Exception e) {
			e.printStackTrace();
		}finally{ session.close();}
		return cliente;
	}

}
